package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.mapper.UserMapper;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.pojo.Audience;
import com.docking.heylo.pojo.Request;
import com.docking.heylo.service.IUserService;
import com.docking.heylo.utils.JwtHelper;
import com.docking.heylo.web.dto.UserDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private Audience audience;


    @Override
    public PageInfo<Map<String, Object>> userList(UserDto userDto) {
        PageHelper.startPage(userDto.getPageNumber(), userDto.getPageSize());
        return new PageInfo<>(userMapper.userList(userDto.getPhone(), userDto.getProfession()));
    }

    @Override
    public Request userForToken(String token) {
        Claims claims = JwtHelper.parseJWT(token, audience.getBase64Secret());
        if(claims == null){
            throw new GeneralException("请求无效");
        }

        Request request = ThreadContext.authorize.get();

        request.setUserId(Integer.parseInt(claims.get("userId").toString()));
        request.setRoleId(Integer.parseInt(claims.get("roleId").toString()));
        request.setUserName(claims.get("userName").toString());
        return request;
    }


}
